package com.demo.datasource.springdatasource_mybatis;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
//@EnableTransactionManagement//已在总开关打开
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = SpringDatasourceConfig.PACKAGE, sqlSessionFactoryRef = "testSqlSessionFactory")
public class SpringDatasourceConfig {

	// 精确到 目录，以便跟其他数据源隔离
	static final String PACKAGE = "com.demo.*.mapper";
	static final String typeAliasesPackage = "com.demo.*.domain";
	static final String MAPPER_LOCATION = "classpath:com/demo/**/mapper/*Mapper.xml";

	@Autowired
	@Qualifier("testDataSource")
	private DataSource testDataSource;

	@Bean(name = "testTransactionManager")
	@Primary
	public DataSourceTransactionManager testTransactionManager() {
		return new DataSourceTransactionManager(testDataSource);
	}

	@Bean(name = "testSqlSessionFactory")
	@Primary
	public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource testDataSource)
			throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(testDataSource);
		sessionFactory.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources(SpringDatasourceConfig.MAPPER_LOCATION));
		sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
		
	    //配置分页插件
//        PageHelper pageHelper = new PageHelper();
//        Properties properties = new Properties();
//        properties.setProperty("reasonable", "true");
//        properties.setProperty("supportMethodsArguments", "true");
//        properties.setProperty("returnPageInfo", "check");
//        properties.setProperty("params", "count=countSql");
//        pageHelper.setProperties(properties);

        //设置插件
//        sessionFactory.setPlugins(new Interceptor[]{pageHelper});
		
		return sessionFactory.getObject();
	}
}
